package util;
import container.Host;
import container.Mapper;
import server.HttpServlet;
import server.Request;
import server.Response;
import java.io.InputStream;
import java.net.Socket;

public class MyRequestProcessor extends Thread {

        private Socket socket;
        private Mapper mapper;

        public MyRequestProcessor(Socket socket, Mapper mapper) {
            this.socket = socket;
            this.mapper = mapper;
        }

        @Override
        public void run() {
            try{
                InputStream inputStream = socket.getInputStream();
                // 封装Request对象和Response对象
                Request request = new Request(inputStream);
                Response response = new Response(socket.getOutputStream());
                Host host = mapper.getHostMap().get(request.getHost());

                if(host!=null){
                    // 静态资源处理
                    if(host.getServletMap().get(request.getUrl()) == null) {
                        response.outputHtml(host.getBaseDir(),request.getUrl());
                    }else{
                        System.out.println("获取动态资源："+request.getUrl()+"存在:"+host.getServletMap().containsKey(request.getUrl()));
                        // 动态资源servlet请求
                        HttpServlet httpServlet = host.getServletMap().get(request.getUrl());
                        httpServlet.service(request,response);
                    }
                }

                socket.close();

            }catch (Exception e) {
                e.printStackTrace();
            }

        }

}
